package com.tester.common;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSONArray;
import com.binance.connector.client.SpotClient;
import com.binance.connector.client.impl.SpotClientImpl;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class UiKlines {

    public static final SpotClient SPOT_CLIENT = new SpotClientImpl("https://data-api.binance.vision");
    public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd-HHmmss");
    public static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#.00");

    /**
     * [[
     * 1499040000000,      // k线开盘时间
     * "0.01634790",       // 开盘价
     * "0.80000000",       // 最高价
     * "0.01575800",       // 最低价
     * "0.01577100",       // 收盘价(当前K线未结束的即为最新价)
     * "148976.11427815",  // 成交量
     * 1499644799999,      // k线收盘时间
     * "2434.19055334",    // 成交额
     * 308,                // 成交笔数
     * "1756.87402397",    // 主动买入成交量
     * "28.46694368",      // 主动买入成交额
     * "17928899.62484339" // 请忽略该参数
     * ]]
     * 转换为
     * <TICKER>,<DTYYYYMMDD>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>
     * XAGUSD,20010102,230300,4.5800,4.5800,4.5800,4.5800,4
     */
    public static void main(String[] args) throws Exception {
        String title = "<TICKER>,<DTYYYYMMDD>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>";
        //测试下载3天的数据
        Date startTime = SIMPLE_DATE_FORMAT.parse("20230101-000000");
        for (int i = 0; i < 1000; i++) {
            if (startTime.getTime() >= DateUtil.parse("2024-01-01 00:00:00").getTime()) {//数据截止时间
                return;
            }
            DateTime endTime = DateUtil.offsetHour(startTime, 12);
            requestBinance(startTime, endTime);
            startTime = endTime;
            TimeUnit.SECONDS.sleep(2);
        }



       /* try {
            FileOutputStream fileOutputStream = new FileOutputStream("output.txt");
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);

            // 将ASCII码写入文件
            outputStreamWriter.write(title);
            outputStreamWriter.write("\n");
            for (int i = 0; i < result.size(); i++) {
                JSONArray k = (JSONArray) result.get(i);
                Date date = new Date(k.getLongValue(0));
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd-HHmmss");
                String[] time = sdf1.format(date).split("-");
                outputStreamWriter.write("ETHUSDT," + time[0] + "," + time[1] + "," + k.get(1) + "," + k.get(2) + "," + k.get(3) + "," + k.get(4) + "," + k.get(5));
                outputStreamWriter.write("\r\n");
            }
            // 关闭输出流
            outputStreamWriter.close();
            fileOutputStream.close();

            System.out.println("ASCII输出到文件成功！");
        } catch (IOException e) {
            System.out.println("ASCII输出到文件失败：" + e.getMessage());
        }*/
    }

    static void requestBinance(Date start, Date end) throws Exception {
        Map<String, Object> parameters = new LinkedHashMap<String, Object>();
        parameters.put("symbol", "ETHUSDT");
        parameters.put("interval", "1m");
//        Date startTime = SIMPLE_DATE_FORMAT.parse("20241203-080000");//yyyyMMdd-HHmmss
//        Date endTime = SIMPLE_DATE_FORMAT.parse("20241203-090000");
        parameters.put("startTime", start.getTime());
        parameters.put("endTime", end.getTime());
        parameters.put("limit", "1000");//默认 500; 最大 1000.
        String response = SPOT_CLIENT.createMarket().uiKlines(parameters);
        JSONArray result = JSONArray.parseArray(response);
        Console.log("开始:{} 截止:{} size:{}", DateUtil.format(start, DatePattern.NORM_DATETIME_MINUTE_PATTERN), DateUtil.format(end, DatePattern.NORM_DATETIME_MINUTE_PATTERN), result.size());
        writeToTxt(result);
    }

    static void writeToTxt(JSONArray result) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\Downloads\\ETH2024.txt", true))) {
            for (int i = 0; i < result.size(); i++) {
                JSONArray k = (JSONArray) result.get(i);
                Date date = new Date(k.getLongValue(0));
                String[] time = SIMPLE_DATE_FORMAT.format(date).split("-");
                writer.write("ETHUSDT," + time[0] + "," + time[1] + ","
                        + DECIMAL_FORMAT.format(k.getDoubleValue(1)) + "," + DECIMAL_FORMAT.format(k.getDoubleValue(2)) +
                        "," + DECIMAL_FORMAT.format(k.getDoubleValue(3)) + "," + DECIMAL_FORMAT.format(k.getDoubleValue(4))
                        + "," + k.getDouble(5).intValue());
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
